package com.example.aslongastoday.db.dao;


import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.aslongastoday.bean.BeanFactory;
import com.example.aslongastoday.db.helper.MyDatabaseHelper;
import com.example.aslongastoday.domain.BackLog;
import com.example.aslongastoday.domain.BackLogGroup;
import com.example.aslongastoday.util.TimeUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class BackLogGroupDao {
    private static volatile BackLogGroupDao dao = null;

    private static MyDatabaseHelper helper;

    private static SQLiteDatabase db;

    public static String BACK_LOG_GROUP_TABLE = "back_log_group";

    private static Gson gson;

    private static String whereClause = "id=?";



    enum Table{

    }
    public void changeData(List<BackLogGroup> backLogGroupList){
        String sql = "truncate table "+BACK_LOG_GROUP_TABLE;

    }

    public BackLogGroupDao(Context context) {
        helper = new MyDatabaseHelper(context);
        db = helper.getWritableDatabase();
        gson = BeanFactory.makeGsonBean();
    }

    //单例模式
    public static BackLogGroupDao getInstance(Context context){
        if(dao == null){
            synchronized (BackLogGroupDao.class){
                if(dao == null){
                    dao = new BackLogGroupDao(context);
                }
            }
        }
        return dao;
    }

    /**
     * 适用于从云端重新加载数据，直接干掉table
     * @param name
     */
    public void dropTable(String name){
        db.execSQL("drop table if exists "+name);
    }

    public void createTable(){
        db.execSQL("create table if not exists "+BACK_LOG_GROUP_TABLE+"(id integer primary key autoincrement," +
                "group_name text,create_time text,back_log_list text) ");
    }

    /**
     * 主要用于更新backLogList
     * @param backLogGroup
     */
    public boolean update(BackLogGroup backLogGroup){
        Integer id = backLogGroup.getId();
        List<BackLog> backLogList = backLogGroup.getBackLogList();
        String groupName = backLogGroup.getGroupName();
        ContentValues values = new ContentValues();
        if(groupName!=null){
            values.put("group_name",groupName);
        }
        if(backLogList!=null){
            values.put("back_log_list",gson.toJson(backLogList));
        }
        String[] whereArgs = {id.toString()};

        db.update(BACK_LOG_GROUP_TABLE,values,whereClause,whereArgs);
        return true;
    }

    public boolean delete(Integer id){
        String[] whereArgs = {id.toString()};
        db.delete(BACK_LOG_GROUP_TABLE,whereClause,whereArgs);

        return true;
    }

    public boolean insert(List<BackLogGroup> list){
//        db.execSQL("drop table if exists back_log_group");

        //防止table被删除，执行一次table，如果存在则不会执行，因为是操作的本地数据库，所以性能损耗可以忽略
        createTable();

        for (BackLogGroup backLogGroup : list) {

            ContentValues cv = new ContentValues();
            cv.put("group_name",backLogGroup.getGroupName());
            cv.put("create_time",backLogGroup.getCreateTime());
            String backLogList = gson.toJson(backLogGroup.getBackLogList());
            cv.put("back_log_list",backLogList);
            cv.put("create_time", TimeUtil.getNowTime());

            db.insert(BACK_LOG_GROUP_TABLE,null,cv);
        }
        return true;
    }

    public BackLogGroup query(Integer id){
        String[] whereArgs = {id.toString()};
        String[] columns = new String[]{"id"};
        Cursor cursor = db.query(BackLogGroupDao.BACK_LOG_GROUP_TABLE,null
                ,whereClause,whereArgs,null,null,null);
        BackLogGroup backLogGroup = new BackLogGroup();


        while (cursor.moveToNext()) {
            @SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex("group_name"));
            @SuppressLint("Range") String createTime = cursor.getString(cursor.getColumnIndex("create_time"));
            @SuppressLint("Range") String back_log_list = cursor.getString(cursor.getColumnIndex("back_log_list"));

            List<BackLog> list =  backLogListFromJson(back_log_list);

            backLogGroup.setId(id);
            backLogGroup.setGroupName(name);
            backLogGroup.setCreateTime(createTime);
            backLogGroup.setBackLogList(list);
        }

        return backLogGroup;
    }

    public List<BackLogGroup> queryFinishedAll(){
        String sql = "select * from "+BACK_LOG_GROUP_TABLE;
        Cursor cursor = db.rawQuery(sql, new String[]{});
        ArrayList<BackLogGroup> backLogGroups = new ArrayList<>();
        while (cursor.moveToNext()) {
            @SuppressLint("Range") Integer id = Integer.valueOf(cursor.getString(cursor.getColumnIndex("id")));
            @SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex("group_name"));
            @SuppressLint("Range") String createTime = cursor.getString(cursor.getColumnIndex("create_time"));
            @SuppressLint("Range") String back_log_list = cursor.getString(cursor.getColumnIndex("back_log_list"));

            List<BackLog> list =  backLogListFromJson(back_log_list);
            for (int i = list.size() - 1; i >= 0; i--) {
                BackLog backLog = list.get(i);
                if (backLog.getStatus()!=1) {
                    list.remove(i);
                }
                backLog.setGroupId(id);
                backLog.setPosition(i);
            }

            BackLogGroup backLogGroup = new BackLogGroup(name, createTime, list);
            backLogGroup.setId(id);
            backLogGroups.add(backLogGroup);
        }

        return backLogGroups;
    }

    public List<BackLogGroup> queryUnfinishedAll(){
        String sql = "select * from "+BACK_LOG_GROUP_TABLE;
        Cursor cursor = db.rawQuery(sql, new String[]{});
        ArrayList<BackLogGroup> backLogGroups = new ArrayList<>();
        while (cursor.moveToNext()) {
            @SuppressLint("Range") Integer id = Integer.valueOf(cursor.getString(cursor.getColumnIndex("id")));
            @SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex("group_name"));
            @SuppressLint("Range") String createTime = cursor.getString(cursor.getColumnIndex("create_time"));
            @SuppressLint("Range") String back_log_list = cursor.getString(cursor.getColumnIndex("back_log_list"));

            List<BackLog> list =  backLogListFromJson(back_log_list);
            for (int i = list.size() - 1; i >= 0; i--) {
                BackLog backLog = list.get(i);
                if (backLog.getStatus()!=0) {
                    list.remove(i);
                }
                backLog.setGroupId(id);
                backLog.setPosition(i);
            }

            BackLogGroup backLogGroup = new BackLogGroup(name, createTime, list);
            backLogGroup.setId(id);
            backLogGroups.add(backLogGroup);
        }

        return backLogGroups;
    }

    public List<BackLogGroup> queryAll(){
        String sql = "select * from "+BACK_LOG_GROUP_TABLE;
        Cursor cursor = db.rawQuery(sql, new String[]{});
        ArrayList<BackLogGroup> backLogGroups = new ArrayList<>();
        while (cursor.moveToNext()) {
            @SuppressLint("Range") Integer id = Integer.valueOf(cursor.getString(cursor.getColumnIndex("id")));
            @SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex("group_name"));
            @SuppressLint("Range") String createTime = cursor.getString(cursor.getColumnIndex("create_time"));
            @SuppressLint("Range") String back_log_list = cursor.getString(cursor.getColumnIndex("back_log_list"));

            List<BackLog> list =  backLogListFromJson(back_log_list);

            BackLogGroup backLogGroup = new BackLogGroup(name, createTime, list);
            backLogGroup.setId(id);
            backLogGroups.add(backLogGroup);
        }

        return backLogGroups;
    }

    private List<BackLog> backLogListFromJson(String json){
        Type type = new TypeToken<List<BackLog>>(){}.getType();
        return  gson.fromJson(json, type);
    }
}
